/*
 * @Author: zhangweinan
 * @Date: 2023-07-17 14:27:07
 * @LastEditors: Hzt
 * @LastEditTime: 2024-11-03 17:37:52
 * @Description: file content
 * @FilePath: \cty_admin\src\permission.js
 */
import router, { error404 } from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import localCache from '@/utils/cache'
import getPageTitle from "@/utils/get-page-title";


NProgress.configure({ showSpinner: false });
const whiteList = ["/login", "/retrievePassword", "/share"];


router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);

  const hasToken = localCache.getCache('token');

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (!store.state.user.loadedRouter) {
        await store
          .dispatch("permission/generatePlatformRoutes")
          .then((accessedRoutes) => {
            router.addRoutes([...accessedRoutes, error404]);
          });
        store.commit("user/SET_RELOAD_ROUTER", true);
        next({ ...to, replace: true });
      }
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // await store.dispatch("user/getInfo");
          next();
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
